package com.banggood.pss.mqtools.bean;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.function.Consumer;

/**
 * @author Mr.chen
 * @date 2020/8/19 8:56
 */
public class HasResultJsonMessageSender extends JsonMessageSender{

    String resultQueueName;

    JsonMessageReceiver jsonMessageReceiver;

    public HasResultJsonMessageSender(String queueName) {
       this(queueName, (String)null);
    }

    public HasResultJsonMessageSender(String queueName, String resultQueueName) {
        super(queueName);
        this.resultQueueName = resultQueueName == null ? queueName + "-$result" : resultQueueName;
        jsonMessageReceiver = new JsonMessageReceiver(this.resultQueueName) {
            @Override
            public void syncHandler(String json) {
                resultHandle(json);
            }

            @Override
            public void handler(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, String json) throws IOException {
                resultHandle(consumerTag, envelope, properties, json);
            }
        };
    }

    public HasResultJsonMessageSender(String queueName, Consumer<String> consumer) {
        super(queueName);
        resultQueueName = queueName + "-$result";
        jsonMessageReceiver = new JsonMessageReceiver(resultQueueName) {
            @Override
            public void syncHandler(String json) {
                consumer.accept(json);
            }

            @Override
            public void handler(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, String json) throws IOException {
                resultHandle(consumerTag, envelope, properties, json);
            }
        };
    }

    /**
     * 返回的结果监听 自动确认
     * @param jsonResult
     */
    public void resultHandle(String jsonResult) {

    }

    /**
     * 更全面的方法
     * @param consumerTag
     * @param envelope
     * @param properties
     * @param json
     * @throws IOException
     */
    public void resultHandle(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, String json) throws IOException {
        resultHandle(json);
        jsonMessageReceiver.getChannel().basicAck(envelope.getDeliveryTag(), false);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        jsonMessageReceiver.channelCreator = this.channelCreator;
        jsonMessageReceiver.afterPropertiesSet();
        jsonMessageReceiver.start();
    }
}
